package cn.wjh.business.controller;

import cn.wjh.business.domain.Language;
import cn.wjh.business.domain.Translate;
import cn.wjh.business.domain.vo.TranslateVo;
import cn.wjh.business.service.ILanguageService;
import cn.wjh.business.service.ITranslateService;
import cn.wjh.common.annotation.Log;
import cn.wjh.common.annotation.RateLimiter;
import cn.wjh.common.core.controller.BaseController;
import cn.wjh.common.core.domain.AjaxResult;
import cn.wjh.common.core.page.TableDataInfo;
import cn.wjh.common.enums.BusinessType;
import cn.wjh.common.enums.LimitType;
import cn.wjh.common.utils.DateUtils;
import cn.wjh.common.utils.uuid.IdUtils;
import cn.wjh.common.utils.uuid.UUID;
import cn.wjh.common.valid.ValidationGroup;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 翻译版本
 */
@RestController
@RequestMapping("/business/Translate")
public class TranslateController extends BaseController {
    @Resource
    private ITranslateService translateService;
    @Resource
    private ILanguageService languageService;

    /**
     * 获取顶级版本列表
     */
    @PreAuthorize("@ss.hasPermi('business:Translate:list')")
    @GetMapping("/topVersionList")
    @Cacheable(value = "translateListCache", keyGenerator = "cacheKeyGenerator")
    public TableDataInfo topVersionList(Translate translate) {
        startPage();
        List<Translate> list = translateService.topVersionList(translate);
        return getDataTable(list);
    }

    /**
     * 查询我的翻译列表
     */
    @PreAuthorize("@ss.hasPermi('business:Translate:list')")
    @GetMapping("/myList")
    public TableDataInfo myList(Translate translate) {
        startPage();
        translate.setUserId(this.getUserId());
        List<Translate> list = translateService.topVersionList(translate);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('business:Translate:query')")
    @GetMapping(value = "/{translateId}")
    @Cacheable(value = "translateListCache", keyGenerator = "cacheKeyGenerator")
    public AjaxResult getInfo(@PathVariable("translateId") Long translateId) {
        return success(translateService.selectTranslateByTranslateId(translateId));
    }

    /**
     * 获取单个翻译值
     */
    @PostMapping("/t")
    @Cacheable(value = "translateListCache", keyGenerator = "cacheKeyGenerator")
    public AjaxResult translate(@RequestBody @Validated(value = ValidationGroup.Query.class) TranslateVo translate) {
        AjaxResult result = AjaxResult.success();
        return result.put(AjaxResult.DATA_TAG, translateService.translateYouDaoOneResult(translate));
    }

    /**
     * 新增翻译版本
     */
    @PreAuthorize("@ss.hasPermi('business:Translate:add')")
    @Log(title = "翻译版本", businessType = BusinessType.INSERT)
    @PostMapping
    @CacheEvict(value = "translateListCache", allEntries = true)
    public AjaxResult add(@RequestBody Translate translate) {
        return toAjax(translateService.insertTranslate(translate));
    }

    /**
     * 修改翻译版本
     */
    @PreAuthorize("@ss.hasPermi('business:Translate:edit')")
    @Log(title = "翻译版本", businessType = BusinessType.UPDATE)
    @PutMapping
    @CacheEvict(value = "translateListCache", allEntries = true)
    public AjaxResult edit(@RequestBody Translate translate) {
        return toAjax(translateService.updateTranslate(translate));
    }

    /**
     * 删除翻译版本
     */
    @PreAuthorize("@ss.hasPermi('business:Translate:remove')")
    @Log(title = "翻译版本", businessType = BusinessType.DELETE)
    @DeleteMapping("/{translateIds}")
    @CacheEvict(value = {"translateListCache", "translateHistoryListCache"}, allEntries = true)
    public AjaxResult remove(@PathVariable List<Long> translateIds) {
        return toAjax(translateService.deleteTranslateByTranslateIds(translateIds));
    }

    /**
     * 保存翻译版本
     */
    @PostMapping("/saveTranslationVersion")
    @CacheEvict(value = {"translateListCache", "translateHistoryListCache"}, allEntries = true)
    public AjaxResult saveTranslationVersion(@RequestBody Translate translate) {
        return toAjax(translateService.saveTranslationVersion(translate));
    }

    /**
     * 有道翻译翻译
     */
    @PostMapping("/translation")
//    @RateLimiter(limitType = LimitType.IP, time = 2, count = 1)
    @CacheEvict(value = "translateHistoryListCache", allEntries = true)
    public AjaxResult translateYouDao(@RequestBody @Validated(value = ValidationGroup.Query.class) TranslateVo translate) {
        return AjaxResult.success(translateService.translateYouDao(translate));
    }

    @PreAuthorize("@ss.hasPermi('business:Translate:import')")
    @Log(title = "翻译模板", businessType = BusinessType.IMPORT)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        List<Language> languages = languageService.list();
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("翻译版本");

            // 创建表头
            Row headerRow = sheet.createRow(0);

            // 获取所有语言 填充语言表头
            for (int i = 0; i < languages.size(); i++) {
                headerRow.createCell(i).setCellValue(languages.get(i).getZhName());
            }
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=importTemplate.xlsx");

            // 输出到响应流
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new SecurityException("模板获取失败,请重试！");
        }

    }


    @PreAuthorize("@ss.hasPermi('business:Translate:import')")
    @Log(title = "翻译版本", businessType = BusinessType.IMPORT)
    @PostMapping("/importAll")
    @CacheEvict(value = "translateListCache", allEntries = true)
    @Transactional
    public AjaxResult importAll(MultipartFile file, Translate translate) {
        translate.setStringKey(null);
        List<Language> list = languageService.list();
        Map<String, String> languageMap = new HashMap<>();
        list.forEach(language -> languageMap.put(language.getZhName(), language.getLanguageCode()));//设置语言映射关系
        String createBy = this.getUsername();
        Long userId = this.getUserId();
        try {
            Workbook workbook = new XSSFWorkbook(file.getInputStream());//解析Excel
//            List<List<Translate>> translationsList = new ArrayList<>();//结果集

            Sheet sheet = workbook.getSheetAt(0);//第一个工作表
            Row headerRow = sheet.getRow(0);//取出表头

            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row currentRow = sheet.getRow(rowIndex);//从第二行开始依次取出数据
                Translate translation = new Translate();//翻译版本对象
                List<Translate> children = new ArrayList<>(); //子集列表
                for (int colIndex = 0; colIndex < headerRow.getLastCellNum(); colIndex++) {
                    Cell headerCell = headerRow.getCell(colIndex);//从第一列开始取出表头
                    Cell currentCell = currentRow.getCell(colIndex);//取出当前列
                    if (currentCell != null && currentCell.getStringCellValue() != null && !currentCell.getStringCellValue().isEmpty()) {
                        //如果是第一列 那就作为源语言
                        if (colIndex == 0) {
                            translation.setProductId(translate.getProductId());//产品
                            translation.setLanguageCode(languageMap.get(headerCell.getStringCellValue()));//语言编码
                            translation.setTranslateVal(currentCell.getStringCellValue());//当前列中的值
                        } else {
                            Translate child = new Translate();//子集
                            child.setLanguageCode(languageMap.get(headerCell.getStringCellValue()));//语言编码
                            child.setTranslateVal(currentCell.getStringCellValue());//当前列中的值
                            children.add(child);
                        }
                    }
                }
                translation.setChildren(children);
                translateService.insertTranslate(translation);//插入
            }
            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            throw new SecurityException("导入失败,请重试！");
        }
    }


    /**
     * 导出翻译版本
     */
    @PreAuthorize("@ss.hasPermi('business:Translate:export')")
    @Log(title = "翻译版本", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAll")
    public void exportAll(HttpServletResponse response, Translate translate) throws IOException {
        translate.setParams(null);
        List<Translate> dataList = translateService.selectTranslateList(translate);
        Map<String, List<Translate>> collect = dataList.stream().collect(Collectors.groupingBy(Translate::getStringKey));
        List<Language> languages = languageService.list();

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("翻译词条");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("StringKey");
            headerRow.createCell(1).setCellValue("所属产品");

            // 获取所有语言 填充语言表头
            for (int i = 0; i < languages.size(); i++) {
                headerRow.createCell(i + 2).setCellValue(languages.get(i).getZhName());
            }
            for (int i = 0; i < languages.size(); i++) {
                int rowIndex = 1; // 第一行是表头，数据从第二行开始
                for (String key : collect.keySet()) {
                    List<Translate> translates = collect.get(key);//取出属于这个key的所有词条
                    Row dataRow = sheet.createRow(rowIndex); //创建一行
                    dataRow.createCell(0).setCellValue(key); // 第一列 填充key
                    int columnIndex = 2; // 第二列开始 填充值
                    for (Language currentLanguage : languages) {//获取当前的语言
                        Translate temp_translate = translates.stream()
                                .filter(t -> t.getLanguageCode().equals(currentLanguage.getLanguageCode())) //过滤出属于当前语言的值
                                .findFirst()//找出第一个
                                .orElse(null);//如果抛出异常 就赋值为null
                        String translateVal = (temp_translate != null) ? temp_translate.getTranslateVal() : "";//没有这个语言的翻译也要填充值
                        if (temp_translate != null) {
                            String productName = temp_translate.getProduct() != null ? temp_translate.getProduct().getProductName() : "";
                            dataRow.createCell(1).setCellValue(productName);//产品名称
                        }
                        dataRow.createCell(columnIndex).setCellValue(translateVal);// 填充
                        columnIndex++;//列++
                    }
                    rowIndex++;//行++
                }
            }
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=TranslateData.xlsx");

            // 输出到响应流
            workbook.write(response.getOutputStream());
        }
    }

}
